/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * © 2024 STMicroelectronics
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "i2c.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "../../Drivers/BSP/LED/led.h"
#include "../../Drivers/BSP/BEEP/beep.h"
#include "../../Drivers/BSP/OLED/oled.h"
#include "../../Drivers/BSP/DS18B20/ds18b20.h"
#include <stdio.h>
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
typedef enum {
    TEMP_IDLE,
    TEMP_RESET,
    TEMP_SKIP_ROM,
    TEMP_CONVERT,
    TEMP_READ,
    TEMP_DONE
} TempState;
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
// 按键标志位
volatile uint8_t key0_flag = 0;
volatile uint8_t key1_flag = 0;

// 防抖相关变量
volatile uint32_t last_interrupt_time_key0 = 0;
volatile uint32_t last_interrupt_time_key1 = 0;
const uint32_t debounce_time = 200; // 200 毫秒防抖

// 状态机变量
volatile TempState temp_state = TEMP_IDLE;
volatile float latest_temperature = 0.0f;
volatile uint32_t start_tick = 0;
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
void Display_Temperature(void);
void Handle_Temperature_State(void);
void Handle_Key0(void);
void Handle_Key1(void);
void Buzzer_Beep(void);
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
// 定时器中断回调函数
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) {
    if (htim->Instance == TIM6) {

    }
}

// 外部中断回调函数
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) {
    uint32_t current_time = HAL_GetTick(); // 获取当前系统时间

    switch (GPIO_Pin) {
        case KEY0_Pin: {
            if ((current_time - last_interrupt_time_key0) > debounce_time) {
                last_interrupt_time_key0 = current_time;
                if (HAL_GPIO_ReadPin(KEY0_GPIO_Port, KEY0_Pin) == GPIO_PIN_RESET) {
                    key0_flag = 1; // 设置标志位
                    printf("KEY0 Pressed\n");
                }
            }
            break;
        }

        case KEY1_Pin: {
            if ((current_time - last_interrupt_time_key1) > debounce_time) {
                last_interrupt_time_key1 = current_time;
                if (HAL_GPIO_ReadPin(KEY1_GPIO_Port, KEY1_Pin) == GPIO_PIN_RESET) {
                    key1_flag = 1; // 设置标志位
                    printf("KEY1 Pressed\n");
                }
            }
            break;
        }
        default:
            break;
    }
}

// UART 接收完成回调
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
    // UART 接收完成回调，在此处理接收到的数据
}

/**
 * @brief 蜂鸣器响0.3秒
 */
void Buzzer_Beep(void) {
    BEEP(1);
    HAL_Delay(300);
    BEEP(0);
}

/**
 * @brief 在OLED上显示温度
 */
void Display_Temperature(void) {
    char temp_str[16];
    float temperature = Ds18b20_Read_Temp();
    if (temperature == 0.0f) {
        snprintf(temp_str, sizeof(temp_str), "Error");
    } else {
        snprintf(temp_str, sizeof(temp_str), "%.2f C", temperature);
    }
    printf("温度： %.2f °C\n", temperature);
    OLED_Clear(); // 清屏
    OLED_ShowCHinese(3, 3, 3, 0); // 温
    OLED_ShowCHinese(19, 3, 4, 0); // 度
    OLED_ShowCHinese(35, 3, 5, 0); // :
    OLED_ShowString(51, 3, temp_str, 16, 0);
}

/**
 * @brief 处理KEY0按键事件：启动温度读取
 */
void Handle_Key0(void) {
    temp_state = TEMP_RESET; // 启动温度读取
    printf("State Change: TEMP_RESET\n");
}

/**
 * @brief 处理KEY1按键事件：清除显示，熄灭LED
 */
void Handle_Key1(void) {
    OLED_Clear();
    LED0(1); // 熄灭LED0
    LED1(1); // 熄灭LED1
    printf("OLED Cleared and LEDs Off\n");
}

/**
 * @brief 处理温度读取状态机
 */
void Handle_Temperature_State(void) {
    switch (temp_state) {
        case TEMP_IDLE:
            // 空闲状态，无操作
            break;

        case TEMP_RESET:
            if (Ds18b20_Reset() == RESET) { // 检测到传感器存在
                printf("State Change: TEMP_SKIP_ROM\n");
                temp_state = TEMP_SKIP_ROM;
            } else {
                printf("State Change: TEMP_IDLE (Sensor not found)\n");
                temp_state = TEMP_IDLE; // 传感器未响应
            }
            break;

        case TEMP_SKIP_ROM:
            Ds18b20_Write_Byte(0xCC); // 跳过ROM
            printf("Sent 0xCC (Skip ROM)\n");
            Ds18b20_Write_Byte(0x44); // 启动温度转换
            printf("Sent 0x44 (Start Temperature Conversion)\n");
            // 记录开始时间
            start_tick = HAL_GetTick();
            temp_state = TEMP_CONVERT;
            break;

        case TEMP_CONVERT:
            // 等待温度转换完成（750毫秒）
            if ((HAL_GetTick() - start_tick) >= 750) {
                printf("State Change: TEMP_READ\n");
                temp_state = TEMP_READ;
            }
            break;

        case TEMP_READ:
            latest_temperature = Ds18b20_Read_Temp();
            if (latest_temperature != 0.0f) {
                printf("Temperature Read: %.2f°C\n", latest_temperature);
                temp_state = TEMP_DONE;
            } else {
                printf("Temperature Read Failed\n");
                temp_state = TEMP_IDLE; // 读取失败，返回空闲状态
            }
            break;

        case TEMP_DONE:
            // 温度读取完成，更新显示
            printf("State Change: TEMP_IDLE (Displaying Temperature)\n");
            Display_Temperature();
            LED0(0); // 点亮LED0
            LED1(0); // 点亮LED1
            temp_state = TEMP_IDLE;
            break;

        default:
            temp_state = TEMP_IDLE;
            break;
    }
}

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART1_UART_Init();
  MX_I2C1_Init();
  MX_TIM6_Init();
  /* USER CODE BEGIN 2 */
    beep_init();
    OLED_Init();

    OLED_Clear();

    OLED_ShowCHinese(3, 3, 0, 0); // 潘
    OLED_ShowCHinese(19, 3, 1, 0); // 子
    OLED_ShowCHinese(35, 3, 2, 0); // 彧

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
    while (1) {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
        // 处理按键标志位
        if (key0_flag) {
            key0_flag = 0; // 清除标志位
            Handle_Key0();
        }

        if (key1_flag) {
            key1_flag = 0; // 清除标志位
            Handle_Key1();
        }

        // 状态机处理温度读取
        Handle_Temperature_State();

        HAL_Delay(10); // 主循环延时，减少CPU占用
    }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */
/* 用户代码已经在前面定义 */
/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
    /* 用户可以在此添加自己的实现来报告 HAL 错误返回状态 */
    __disable_irq();
    while (1) {
    }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
    /* 用户可以在此添加自己的实现来报告文件名和行号，例如：
       printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
